package com.cly.common.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cly.common.exception.CommonException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    /**
     * 生产JWT
     * @param secreKey jwt密钥
     * @param time      jwt过期时限
     * @param userId    封装的信息
     * @return
     */
    public static String getJWT(String secreKey, long time, Long userId){
        return JWT.create() // 生产Builder对象进行创建JWT
                .withClaim("userId", userId) // 需要封装的数据
                .withExpiresAt(new Date(System.currentTimeMillis() + time)) // 设置过期时间
                .sign(Algorithm.HMAC256(secreKey));
    }


    /**
     * Token解密
     *
     * @param token     加密后的token
     * @return
     */
    public static Long parseToken(String token, String secretKey){
        try {
            DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(secretKey))
                    .build()
                    .verify(token);
            return decodedJWT.getClaim("userId").asLong();
        } catch (Exception e) {
            throw new CommonException("token无效",e);
        }
    }
}
